package com.atguigu.crowd.funding.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.atguigu.crowd.funding.entity.ResultEntity;
import com.atguigu.crowd.funding.util.CorwdUtil;
import com.atguigu.crowd.funding.util.CrowdFundingConstant;
import com.google.gson.Gson;

/**
 * 异常处理机制
 * @author Administrator
 *
 */
@ControllerAdvice
public class CrowdFundingExceptionResolever {

	@ExceptionHandler(value=Exception.class)
	public ModelAndView cathException(Exception e,
			HttpServletRequest request,
			HttpServletResponse response) throws IOException{
	
		//1.判断请求是否是异步请求
		if(CorwdUtil.isAsyncRequest(request)){
			//根据异常信息，使用自定义的友好异常提示
			String exceptionName = e.getClass().getName();
			
			String msg=CrowdFundingConstant.EXCEPTION_MSG_MAP.get(exceptionName);
			if(msg==null){
				msg="系统未知异常："+e.getMessage();
			}
			
			//创建返回结果类，自定义
			ResultEntity<String> result=ResultEntity.failed(msg);
			//将返回实体转为json数据
			Gson gson = new Gson();
			String json = gson.toJson(result);
			
			//设置响应头为json,编写响应信息
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(json);
			
			return null;
			
		}
		
		ModelAndView mv=new ModelAndView();
		mv.addObject("exception", e);
		mv.setViewName("system-error");
		
		return mv;
	}
}
